import type { IQueue, ObjStack } from "../../types";

/**
 * @description 对象实现的队列;FIFO；时间复杂度O(1)
 * @author hzq
 * @date 2025-04-10 13:37:10
 */
class Queue<T> implements IQueue<T> {
  private items: ObjStack<T>;
  private count: number;
  /**
   * 记录队列中第一个元素的位置
   */
  private lowestCount: number;
  constructor() {
    this.items = {};
    this.count = 0;
    this.lowestCount = 0;
  }

  dequeue(): T | undefined {
    if (this.isEmpty()) {
      return void 0;
    }
    const result = this.items[this.lowestCount];
    delete this.items[this.lowestCount];
    this.lowestCount++;
    return result;
  }

  enqueue(...args: T[]): void {
    args.forEach((item) => {
      this.items[this.count] = item;
      this.count++;
    });
  }

  front() {
    return this.isEmpty() ? void 0 : this.items[this.lowestCount];
  }

  isEmpty() {
    return this.size() === 0;
  }

  size() {
    return this.count - this.lowestCount;
  }

  clear() {
    this.items = {};
    this.count = 0;
    this.lowestCount = 0;
  }

  toString() {
    return this.isEmpty() ? null : `Queue [${this.front()},...rest]`;
  }
}

export default Queue;
